<template>
  <page-header-wrapper>
    <a-card :bordered='false'>
      <a-form :label-col='{span:8}' :wrapper-col='{span:16}'>
        <a-row :gutter='48'>
          <a-col :span='6'>
            <a-form-item label='角色名称'>
              <a-input v-model='queryParam.name' placeholder='请输入角色名称' />
            </a-form-item>
          </a-col>
          <a-col :span='6'>
            <a-form-item label='角色状态'>
              <a-select v-model='queryParam.status' placeholder='请选择角色状态' default-value='0' style='width: 100%;'>
                <a-select-option :value='0'>关闭</a-select-option>
                <a-select-option :value='1'>启用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <span class='table-page-search-submitButtons' :style="{ float: 'right', overflow: 'hidden' } ">
              <a-button type='primary' @click='getTableData'>查询</a-button>
              <a-button style='margin-left: 8px' @click='resetQueryParams'>重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
      <a-divider />
      <a-button type='primary' @click='AddItem'>
        新增
      </a-button>
      <a-table bordered :data-source='dataSource' :columns='columns' style='margin-top: 20px' :loading='loading'
               :rowKey='"id"'
               :pagination='{
                 current: queryParam.pageNum,
                 pageSize: queryParam.pageSize,
                 total: total,
               }'
               @change='changeTable'
      >
        <template slot='status' slot-scope='text, record'>
          <a-tag color='orange' v-if="text===1">
            启用中
          </a-tag>
          <a-tag color='gray' v-if="text===0">
            待启用
          </a-tag>
        </template>
        <template slot='operation' slot-scope='text, record'>
          <a-space>
            <a-button type='link' @click='editItem(record)'>编辑</a-button>
            <a-button type='link' @click='menuEdit(record)'>菜单设置</a-button>
            <a-popconfirm title='是否要删除选中菜单?' ok-text='确认' cancel-text='取消' @confirm='deleteItem(record)'>
              <a-button type='link' style='color:red'>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal :width="800" v-model="visible" :title="modalTitle" @ok="submit" @cancel='modalCancel'>
      <a-form-model
        ref="editForm"
        :model="editForm"
        :rules="editFormRules"
        :label-col="{span:6}"
        :wrapper-col="{span: 16}"
      >
        <a-form-model-item ref="id" label="角色id" prop="id" :hidden='true'>
          <a-input v-model="editForm.id" />
        </a-form-model-item>
        <a-form-model-item ref="name" label="角色名称" prop="name">
          <a-input v-model="editForm.name" placeholder='请输入角色名称'/>
        </a-form-model-item>
        <a-form-model-item ref="descName" label="角色描述" prop="descName">
          <a-input v-model="editForm.descName" placeholder='请输入角色描述'/>
        </a-form-model-item>
        <a-form-model-item label="角色状态" prop="status">
          <a-select v-model="editForm.status" placeholder="请选择角色状态">
            <a-select-option :value=1>
              启用中
            </a-select-option>
            <a-select-option :value=0>
              待启用
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal :width="800" v-model="menuVisible" title="菜单设定" @ok="menuSubmit" @cancel='menuModalCancel'>
      <a-tree
        v-if='treeData.length > 0'
        :defaultExpandAll="true"
        v-model="checkedKeys"
        checkable
        :auto-expand-parent="autoExpandParent"
        :tree-data="treeData"
        :checkStrictly='true'
      />
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { resetFormValue, setFormValue } from '@/utils/formUtils'
import { roleAdd, roleDeleteById, roleList, roleMenuAdd, roleUpdateById } from '@/api/system/roleManage'
import { menuList } from '@/api/system/menuManage'

const columns = [
  {
    title: '角色名称',
    dataIndex: 'name'
  },
  {
    title: '角色描述',
    dataIndex: 'descName'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '角色状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
    width: '200px'
  }
]

// 数组转树
function arrayToTree(array, parentId = 0) {
  const result = [];
  for (let item of array) {
    item.title = item.meta.title
    item.key = item.id
    item.value = item.id
    if (item.parentId === parentId) {
      const children = arrayToTree(array, item.id);
      if (children.length) {
        item.children = children;
      }
      result.push(item);
    }
  }
  return result;
}

export default {
  name: 'roleManage',
  data() {
    return {
      // 查询参数
      queryParam: {
        pageSize: 10,
        pageNum: 1,
        name: undefined,
        status: undefined
      },
      columns: columns,
      dataSource: [],
      total:0,
      visible: false,
      menuVisible: false,
      loading: false,
      modalTitle: '新增',
      // 编辑弹窗
      editForm:{
        id:undefined,
        name:undefined,
        descName: undefined,
        status:undefined
      },
      editFormRules:{
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' },],
        descName: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
        status: [{ required: true, message: '请选择角色状态', trigger: 'change' }],
      },
      // 菜单树相关
      editRoleId: '',
      treeData: [],
      checkedKeys:[],
      autoExpandParent: true,
    }
  },
  created(){
    this.getTableData()
    this.initTreeData()
  },
  methods: {
    getTableData() {
      console.log(this.queryParam)
      this.loading = true
      roleList(this.queryParam).then((res)=>{
        console.log(res)
        this.dataSource = res?.data?.records || []
        this.total = res?.data?.total || 0
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
    },
    changeTable(pagination){
      console.log(pagination)
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      this.getTableData()
    },
    resetQueryParams(){
      this.queryParam = {
        pageSize: 10,
        pageNum: 1,
        name: undefined,
        status: undefined
      }
    },
    AddItem() {
      console.log('点击了新增')
      this.modalTitle = '新增'
      this.visible = true
    },
    editItem(record){
      this.modalTitle = '编辑'
      setFormValue(this.editForm,record)
      this.visible = true;
    },
    modalCancel(){
      this.visible = false
      resetFormValue(this.editForm)
    },
    deleteItem(record){
      console.log('删除数据')
      roleDeleteById(record).then(res=>{
        this.$message.success('删除成功')
        this.getTableData()
      })
    },
    submit(){
      this.$refs.editForm.validate().then(()=>{
        console.log('提交表单',this.editForm)
        const api = this.editForm.id ? roleUpdateById : roleAdd
        api(this.editForm).then(res => {
          console.log(res)
          this.$message.success('操作成功')
          resetFormValue(this.editForm)
          this.visible = false;
          this.getTableData()
        })
      }).catch((err)=>{
        console.log(err)
      })
    },
    initTreeData(){
      menuList().then((res)=>{
        let dataList = res.data.dataList
        this.originMenuList = dataList
        let root = {
          key: 0,
          value:0,
          title:'顶点',
          children:[]
        }
        let tree = arrayToTree(dataList)
        console.log(tree)
        root.children = tree
        this.treeData = [root]
        // console.log(this.treeData)
      })
    },
    menuEdit(item){
      this.menuVisible = true
      this.editRoleId = item.id
    },
    menuSubmit(){
      console.log(this.checkedKeys)
      let menuList = this.checkedKeys.checked.filter((item)=>item!==0).map(v=>{
        return {
          menuId: v,
          status: '1'
        }
      })
      let params = {
        roleId: this.editRoleId,
        menuList
      }
      roleMenuAdd(params).then(()=>{
        this.$message.success('配置菜单成功')
      })
    },
    menuModalCancel(){
      this.menuVisible = false
    }
  }
}
</script>

<style scoped>


</style>